package admin

import (
	v1 "last/app/controllers/v1"
	adminModel "last/app/models/admin"
	"last/app/requests"
	adminRequest "last/app/requests/admin"
	"last/pkg/jwt"
	"last/pkg/password"
	"last/pkg/respose"
	"time"

	"github.com/gin-gonic/gin"
)

// LoginController 登陆
type LoginController struct {
	v1.BaseController
}

// Login 登陆
func (l LoginController) Login(c *gin.Context) {
	var params adminRequest.AdminParams
	err := requests.Validator(&params, c)
	if err != nil {
		respose.Failed(c, err.Error())
		return
	}
	
	var adminInfo = &adminModel.Admins{}
	//数据库查询
	SqlErr :=  adminModel.LoginByUserName(params.UserName,adminInfo)
	if SqlErr != nil || !password.ValidatePasswords(adminInfo.Password,params.Password){
		respose.Failed(c, "账号或密码错误")
		return
	}


	//生成 jwt 的 token
	token, err := jwt.GenerateToken(params.UserName, time.Now().Add(60*24*time.Hour))
	if err != nil {
		respose.Failed(c, "系统错误,token 生成错误")
		return
	}
	result := make(map[string]interface{})
	result["token"] = token
	respose.Success(c, result, "登陆成功")
}
